package com.flume.sample


import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

/**
 *
 */
class ShapeView : View {

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet? = null) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    private val paint = Paint()

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //设置背景色
        canvas.drawARGB(255, 139, 197, 186)
        drawShape(0,canvas)
        drawShape(1,canvas)
        drawShape(2,canvas)
        drawShape(3,canvas)
    }

    private fun drawShape(type: Int,canvas: Canvas) {
        val canvasWidth = width
        val r = (canvasWidth / 8).toFloat()

        when(type){
            0 -> paint.let {
                //绘制黄色的圆形
                it.color = Color.YELLOW
                canvas.drawCircle(r, r, r, it)
                //绘制蓝色的矩形
                it.color = Color.BLUE
                canvas.drawRect(r, r, r * 2.7f, r * 2.7f, it)
            }
            1 -> paint.let {
                val layerId = canvas.saveLayer(
                    0F, 0F,
                    canvasWidth.toFloat(), canvas.height.toFloat(), null, Canvas.ALL_SAVE_FLAG
                )
                val y = r*4
                //绘制黄色的圆形
                //it.color = Color.YELLOW
                it.color = Color.parseColor("#55000000")
                canvas.drawCircle(r, y, r, it)

                //paint.xfermode =  PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)
                paint.xfermode =  PorterDuffXfermode(PorterDuff.Mode.SRC_IN)

                //绘制蓝色的矩形
                it.color = Color.BLUE
                canvas.drawRect(r, y, r * 2.7f, y + r * 1.7f, it)


                paint.xfermode = null
                canvas.restoreToCount(layerId)
            }
        }
    }

}